<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/27
 * Time: 14:22
 */
namespace app\index\model;

use think\Db;

class Base extends \think\Model
{
    private $tableName;
    private $zeroTime = "";//当天0点
    private $endTime = "";

    /**
     * @return string
     */
    public function getEndTime()
    {
        return mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
    }


    /**
     * @return string
     */
    public function getZeroTime()
    {
        return mktime(0,0,0,date('m'),date('d'),date('Y'));
    }

    /**
     * @return mixed
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * @param mixed $tableName
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }//表名

    /*
     * 添加
     * */
    public function add($data)
    {
        $id = Db::name($this->tableName)->insertGetId($data);
        return $id ? $id : "";
    }

    /*
     * 修改
     * */
    public function edit($data)
    {
        return Db::name($this->tableName)->update($data) ? 1 : 0;

    }

    /*
     * 根据id批量删除
     * */
    public function deleteByIds($ids){
        return Db::name($this->tableName)->where("id","in",$ids)->delete();
    }

    /*
     * 根据条件查询分页系统 如:($id=>1)
     * @param int $limit |获取多少条
     * @param string $sort |排序模式 desc|asc
     * @param string $col  |需要排序的字段默认为id
     * */
    public function selectByKVPage($data="", $limit = 20,$sort = "desc", $col = "id")
    {
        if($data) {
            $arr = Db::name($this->tableName)->where($data)->order("$col $sort")->paginate($limit);
        }else{
            $arr = Db::name($this->tableName)->order("$col $sort")->paginate($limit);
        }

        return $arr ? $arr : 404;
    }
    /*
     * 自定义分页查询
     * @param int $limit |获取多少条
     * @param int $page  |当前分页
     * @param string $sort |排序模式 desc|asc
     * @param string $col  |需要排序的字段默认为id
     * */
    public function mySelectByKVPage($data="",$page=0, $limit = 20,$sort = "desc", $col = "id")
    {
        if($data) {
            $arr = Db::name($this->tableName)->where($data)->order("$col $sort")->limit($page*$limit,$limit)->select();
        }else{
            $arr = Db::name($this->tableName)->order("$col $sort")->limit($page*$limit,$limit)->select();
        }

        return $arr ? $arr : 404;
    }

    /*
     * 根据id查询
     * */
    public function findById($id)
    {
        return Db::name($this->tableName)->where("id", $id)->find();
    }

    /*
     * 根据键值对查询
     * @param  array $data 查询条件
     * */
    public function findByKV($data,$in=false)
    {
        return $in===false ?  Db::name($this->tableName)->where($data)->find()
            : Db::name($this->tableName)->where($data['key'],'in',$data['value'])->find() ;
    }


    /*
     *根据键值对批量查询
     * @param array $data 查询条件
     * */
    public function selectByKV($data){
        return  Db::name($this->tableName)->where($data)->select();
    }

    /*
       * 查询该表所有数据
       * */
    public function selectAll(){
        return Db::name($this->tableName)->select();
    }
    /*
     * 根据键值对条件统计条数
     * */
    public function countByKey($data="")
    {
        return is_array($data) ?  Db::name($this->tableName)->where($data)->count() : Db::name($this->tableName)->count() ;
    }

    /*
     * 统计当天的数据
     * @param $row  要区分的字段
     * @param $mode 模式
     * @param $timeRow 时间字段名称
     * */
    public function countByDay($row="*",$mode="count",$timeRow="createTime")
    {
        $zeroTime = "date_format(now(), '%Y-%m-%d 00:00:00')";//当天0点
        $endTime = "date_format(now(), '%Y-%m-%d 23:59:59')";//当天23:59:59

        $sql =$row!="*"&&$mode=="count" ? "SELECT $mode($row) as $row FROM ".$this->getTableName()." WHERE  $timeRow >$zeroTime
        AND $timeRow < $endTime  GROUP BY $row LIMIT 2"
            : "SELECT $mode($row) $row  FROM ".$this->getTableName()." WHERE  $timeRow >$zeroTime
        AND $timeRow < $endTime  LIMIT 1"
        ;
        return Db::query($sql);
    }



    /**
     * 根据条件删除单条记录
     */
    public function delByKV($data)
    {
        return Db::name($this->tableName)->where($data)->delete();
    }


    /*
     * 访问https链接
     * */
    public function http_request($url, $model = "get", $arr = "", $timeout = 30, $header = array())
    {
        //echo  $url."model:".$model;
        $curl = curl_init();
        $headers = [
            "access_token:" . '$SUPER_USER_ACCESS_TOKEN$'
            , "content-type: application/json"];
        if ($model == "POST") {
            curl_setopt($curl, CURLOPT_URL, $url);//请求链接
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($arr));//请求数据
        } else if ($model == "GET") {
            if (isset($arr['key'])) {

                curl_setopt($curl, CURLOPT_URL, $url . "?" . $arr['key'] . "=" . urlencode($arr['value']));//是否携带参数
                // echo $url . "?" . $arr['key'] . "=" . urlencode($arr['value']);
            } else {
                $arr ? curl_setopt($curl, CURLOPT_URL, $url . "/" . $arr['value']) : curl_setopt($curl, CURLOPT_URL, $url);//是否携带参数
            }
        } else {
            curl_setopt($curl, CURLOPT_URL, $url);//请求链接
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $model);//请求方式
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($arr));//请求数据
        }

        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置提交方式

        $data = curl_exec($curl);
        curl_close($curl);
        return $data; //判断返回数据还是状态码
    }

    /*
* 核心加密方法2
* */
    public function encrypt($string, $operation, $key = '')
    {
        $key = md5($key);
        $key_length = strlen($key);
        $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return '';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }
    }

}